package net.zoneland.x.bpm.mobile.v1.zoneXBPM

import HttpCacheUtil
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.ext.copyToAlbum
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.utils.CheckRoot
import net.zoneland.x.bpm.mobile.v1.zoneXBPM.utils.FileUtil
import java.io.File

class MainActivity: FlutterFragmentActivity() {
    private val pluginName = "o2oa.net/flutter_inner" // 插件通道名称
    private val tag = "MainActivity"
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
//        flutterEngine.plugins.add(MyFlutterPlugin())
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, pluginName).setMethodCallHandler { methodCall, result ->
            when(methodCall.method) {
                "openFile" -> openFileWithDefaultApp(methodCall.argument<String>("filePath"), result)
                "installAPK" -> installApk(methodCall.argument<String>("filePath"), result)
                "clearCache" -> clearCache(result)
                "checkRoot" -> checkRoot(result)
                "saveToAlbum" -> saveToAlbum(methodCall.argument<String>("filePath"), result)
                "isTabletDevice" -> isTabletDevice(result)
                "initBaiduSdk" -> initBaiduSdk(result)
                else -> result.notImplemented()
            }
        }
    }

    /**
     * 初始化百度 sdk
     * 同意协议后执行
     */
    private fun initBaiduSdk(result: MethodChannel.Result) {
        try {
            O2App.instance.initBaiduSdk()
            result.success(true)
        } catch (e: Exception) {
            result.error("UNAVAILABLE", "初始化百度 sdk 失败", e)
        }
    }

    /**
     * 是否平板 pad
     */
    private fun isTabletDevice(result: MethodChannel.Result)  {
        Log.i(tag,"isTabletDevice 方法执行 ")
        try {
            val screenlayout =  MainActivity@this.resources.configuration.screenLayout
            val isPad =  (screenlayout.and(Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE)
            Log.i(tag,"isPad $isPad ")
            val wm = MainActivity@this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val display = wm.defaultDisplay
            val dm = DisplayMetrics()
            display.getMetrics(dm)
            val x = Math.pow((dm.widthPixels / dm.xdpi).toDouble(), 2.0)
            val y = Math.pow((dm.heightPixels / dm.ydpi).toDouble(), 2.0)
            val screenInches = Math.sqrt(x + y) // 屏幕尺寸
            Log.i(tag,"screenInches $screenInches ")
            result.success(( isPad || screenInches >= 7.0))
        } catch (e: Exception) {
            result.error("UNAVAILABLE", "isTabletDevice查询失败", e)
        }
    }

    /**
     * 保存图片到相册
     */
    private fun saveToAlbum(filePath: String?, result: MethodChannel.Result) {
        try {
            if (TextUtils.isEmpty(filePath)) {
                result.error("UNAVAILABLE", "保存到相册失败，没有传入filePath", null)
                return
            }
            val file = File(filePath!!)
            if (!file.canRead() || !file.exists()) {
                Log.w(tag, "check: read file error: $file")
                result.error("UNAVAILABLE", "保存到相册失败，无法读取到文件！", null)
                return
            }
            file.copyToAlbum(this, file.name, null);
            result.success(true)
        } catch (e: Exception) {
            result.error("UNAVAILABLE", "保存到相册失败", e)
        }
    }
 


    /**
     * 检查系统是否 root
     */
    private fun checkRoot(result: MethodChannel.Result) {
        try {
            result.success(CheckRoot.isDeviceRooted())
        } catch (e: Exception) {
            result.error("UNAVAILABLE", "检查 root 失败", e)
        }
    }

    /**
     * 清除缓存
     */
    private fun clearCache(result: MethodChannel.Result) {
        try {
            HttpCacheUtil.clearCache(this, 0)
            result.success(null)
        } catch (e: Exception) {
            result.error("UNAVAILABLE", "清除缓存错误", e)
        }
    }

    /**
     * 启动安装 apk
     */
    private fun installApk(filePath: String?, result: MethodChannel.Result) {
        Log.i(tag,"installApk 方法执行 ")
        try {
            if (filePath == null || TextUtils.isEmpty(filePath)) {
                result.error("UNAVAILABLE", "没有传入 filePath！", null)
                return
            }
            val file = File(filePath)
            if (!file.exists()) {
                result.error("UNAVAILABLE", "文件不存在！", null)
                return
            }
            val uri = FileUtil.getUriFromFile(applicationContext, file)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addCategory("android.intent.category.DEFAULT")
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val type = FileUtil.getMIMEType(file)
            Log.i(tag,"文件类型:$type")
            intent.setDataAndType(uri, type)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)//这个参数要添加， 不然关闭应用之后再点击通知栏会报错
            startActivity(intent)
            result.success(null)
        } catch (e: Exception) {
            result.error("UNAVAILABLE", "文件打开错误", e)
        }
    }

    /**
     * 用系统默认app打开文件
     */
    private fun openFileWithDefaultApp(filePath: String?, result: MethodChannel.Result) {
        Log.i(tag,"openFileWithDefaultApp 方法执行 ")
        try {
            if (filePath == null || TextUtils.isEmpty(filePath)) {
                result.error("UNAVAILABLE", "没有传入 filePath！", null)
                return
            }
            val file = File(filePath)
            if (!file.exists()) {
                result.error("UNAVAILABLE", "文件不存在！", null)
                return
            }
            val intent = Intent()
            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //设置intent的Action属性
            intent.action = Intent.ACTION_VIEW
            //获取文件file的MIME类型
            val type = FileUtil.getMIMEType(file)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                val contentUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", file)
                intent.setDataAndType(contentUri, type)
            } else {
                intent.setDataAndType(Uri.fromFile(file), type)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            startActivity(intent)
            result.success(null)
        } catch (e: Exception) {
            result.error("UNAVAILABLE", "文件打开错误", e)
        }
    }
}
